﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(SubMeshNormal))]
public class SubMeshNormalEditor : Editor
{
    public override void OnInspectorGUI()
    {
        var mm = (SubMeshNormal)target;
        base.OnInspectorGUI();
        if (GUILayout.Button("Update"))
        {
            mm.UpdateNormals();
        }
    }
}
#endif

public class SubMeshNormal : MonoBehaviour
{
    public Transform target;
    //public List<Vector3> normals;
    private Vector3[] normals;
    private List<Vector3> normalsOrigin;
    public Vector3 add;
    Mesh mesh;
    Vector3 dir;
    public float weight;
    public float lineLength;
    public bool showLine;
    int[] tris;
    Vector3[] vertices;
    private void Start()
    {
        var smr = GetComponent<SkinnedMeshRenderer>();
        var mesh = Instantiate(smr.sharedMesh);
        smr.sharedMesh = mesh;
        normalsOrigin = new List<Vector3>();
        mesh.GetNormals(normalsOrigin);
        normals = normalsOrigin.ToArray();
        tris = mesh.triangles;//mesh.GetTriangles(0); // submesh
        vertices = mesh.vertices;
    }
    public void UpdateNormals()
    {
        dir = target.up;
        foreach (var i in tris)
        {
            var origin = transform.TransformDirection(normalsOrigin[i]);
            normals[i] = Vector3.Lerp(origin, dir, weight); ;
            normals[i] += add;
            normals[i] = normals[i].normalized;
            normals[i] = transform.InverseTransformDirection(normals[i]);
        }
        //mesh.SetNormals(normals);
        GetComponent<SkinnedMeshRenderer>().sharedMesh.normals = normals;
    }
    public void Update()
    {
        foreach (var i in tris)
        {
            var v = transform.TransformPoint(vertices[i]);
            if (showLine) Debug.DrawLine(v, v + normals[i] * lineLength, Color.red);
        }
    }
}
